package LeetCode.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 * @author: leiwenkang02@meituan.com
 * @date: 2018/8/28
 * @time: 16:16
 */
public class Test01两数之和 {
    public static void main(String[] args) {
        int[] nums = {2, 7 ,11, 15, 6, 4, 5};
        int[] result = twoSum(nums, 13);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }
    //O（n）
    public static int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return null;
        }
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = i;
                result[1] = map.get(target - nums[i]);
                return result;
            }
            map.put(nums[i], i);
        }
        return null;

    }

    //O（n2）
    public static int[] twoSum2(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return null;
        }
        int[] result = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return null;
    }
}
